<?php
declare (strict_types=1);

namespace app\common\middleware;

use app\common\model\AdminLog as DataMode;

class Log
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $app = strtolower(app('http')->getName());
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $url = strtolower($request->url());
        if ($request->isAjax() || $request->isPost()) {
            switch ($action) {
                case 'add'://新增
                    $type =1;
                    break;
                case 'edit'://修改
                case 'upfield'://字段修改
                    $type =2;
                    break;
                case 'delete'://删除
                    $type =3;
                    break;
                case 'alldelete'://批量删除
                    $type =4;
                    break;
                case 'detail'://查看日志
                    $type = !empty(input('id')) ? 5 : '';
                    break;
                case 'login'://登录日志
                    $type = 6;
                    break;
                case 'inexcel'://导入
                    $type = 7;
                    break;
                case 'outexcel'://导出
                    $type = 8;
                    break;
            }
            if (!empty($type) && $controller!='logc') {
                $updata = [
                    'type' => $type,
                    'module' => $app,
                    'controller' => $controller,
                    'action' => $action,
                    'method' => $request->method(),
                    'url' => $url,
                    'post_data' => json_encode($request->post(), JSON_UNESCAPED_UNICODE),
                    'get_data' => json_encode($request->get(), JSON_UNESCAPED_UNICODE),
                    'headers' =>json_encode($request->header(), JSON_UNESCAPED_UNICODE),
                    'agent' => $request->server('HTTP_USER_AGENT'),
                    'ip' => $request->ip(),
                    'create_time' => date('Y-m-d H:i:s'),
                    'create_id' => GetToken('id') ?: 0,
                ];
                $Model = new DataMode();
                $Model->insert($updata);
            }
        }
        return $next($request);
    }
}